import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/sillytavern_chat_controller.dart';
import '../services/sillytavern_service.dart';

/// SillyTavern聊天页面
class SillyTavernChatPage extends StatelessWidget {
  final controller = Get.put(SillyTavernChatController());
  final textController = TextEditingController();
  final scrollController = ScrollController();

  SillyTavernChatPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: Obx(() {
        if (!controller.isInitialized.value) {
          return _buildLoadingView();
        }

        if (controller.selectedCharacter.value == null) {
          return _buildEmptyView('请选择一个角色开始聊天');
        }

        if (controller.selectedSession.value == null) {
          return _buildEmptyView('请选择或创建一个会话');
        }

        return _buildChatView();
      }),
    );
  }

  /// 构建AppBar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Obx(() {
        if (controller.selectedCharacter.value != null) {
          // 如果有故事标题，显示为副标题
          if (controller.storyTitle != null && controller.storyTitle!.isNotEmpty) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  controller.selectedCharacter.value!.name,
                  style: TextStyle(fontSize: 18),
                ),
                Text(
                  '故事: ${controller.storyTitle}',
                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.normal),
                ),
              ],
            );
          }
          return Text(controller.selectedCharacter.value!.name);
        }
        return Text('SillyTavern 聊天');
      }),
      actions: [
        // 角色选择
        IconButton(
          icon: Icon(Icons.person),
          tooltip: '选择角色',
          onPressed: _showCharacterSelector,
        ),
        // ========== 已隐藏：会话管理（现在自动管理） ==========
        // IconButton(
        //   icon: Icon(Icons.chat_bubble_outline),
        //   tooltip: '会话管理',
        //   onPressed: _showSessionManager,
        // ),
        // ============================================
        // 角色信息
        Obx(() {
          if (controller.selectedCharacter.value != null) {
            return IconButton(
              icon: Icon(Icons.info_outline),
              tooltip: '角色信息',
              onPressed: _showCharacterInfo,
            );
          }
          return SizedBox.shrink();
        }),
      ],
    );
  }

  /// 加载视图
  Widget _buildLoadingView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('正在初始化...'),
        ],
      ),
    );
  }

  /// 空白视图
  Widget _buildEmptyView(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.chat_bubble_outline,
            size: 64,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16),
          Text(
            message,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 24),
          if (controller.selectedCharacter.value == null)
            ElevatedButton.icon(
              onPressed: _showCharacterSelector,
              icon: Icon(Icons.person),
              label: Text('选择角色'),
            ),
          // ========== 已隐藏：创建新会话（现在自动管理） ==========
          // else
          //   ElevatedButton.icon(
          //     onPressed: () => controller.createNewSession(),
          //     icon: Icon(Icons.add),
          //     label: Text('创建新会话'),
          //   ),
          // ============================================
        ],
      ),
    );
  }

  /// 聊天视图
  Widget _buildChatView() {
    return Column(
      children: [
        // 消息列表
        Expanded(
          child: Obx(() {
            if (controller.isLoading.value) {
              return Center(child: CircularProgressIndicator());
            }

            final displayMessages = controller.displayMessages;

            if (displayMessages.isEmpty) {
              return Center(
                child: Text(
                  '暂无消息，开始对话吧！',
                  style: TextStyle(color: Colors.grey[600]),
                ),
              );
            }

            // 滚动到底部
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (scrollController.hasClients) {
                scrollController.animateTo(
                  scrollController.position.maxScrollExtent,
                  duration: Duration(milliseconds: 300),
                  curve: Curves.easeOut,
                );
              }
            });

            return ListView.builder(
              controller: scrollController,
              padding: EdgeInsets.all(16),
              itemCount: displayMessages.length,
              itemBuilder: (context, index) {
                return _buildMessageItem(displayMessages[index]);
              },
            );
          }),
        ),

        // 输入框
        _buildInputArea(),
      ],
    );
  }

  /// 消息气泡
  Widget _buildMessageItem(STMessage message) {
    final isUser = message.isUser;

    return Padding(
      padding: EdgeInsets.only(bottom: 16),
      child: Row(
        mainAxisAlignment:
            isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isUser) ...[
            // AI头像
            CircleAvatar(
              radius: 20,
              backgroundColor: Colors.purple[100],
              child: Text(
                message.name.isNotEmpty ? message.name[0] : 'A',
                style: TextStyle(color: Colors.purple[700]),
              ),
            ),
            SizedBox(width: 8),
          ],

          // 消息内容
          Flexible(
            child: Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: isUser ? Colors.blue[100] : Colors.grey[200],
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 名称
                  Text(
                    message.name,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 12,
                      color: isUser ? Colors.blue[900] : Colors.grey[800],
                    ),
                  ),
                  SizedBox(height: 4),

                  // 消息文本
                  Text(
                    message.mes,
                    style: TextStyle(fontSize: 15),
                  ),
                  SizedBox(height: 4),

                  // 时间
                  Text(
                    message.formattedTime,
                    style: TextStyle(
                      fontSize: 10,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
          ),

          if (isUser) ...[
            SizedBox(width: 8),
            // 用户头像
            CircleAvatar(
              radius: 20,
              backgroundColor: Colors.blue[100],
              child: Text(
                message.name.isNotEmpty ? message.name[0] : 'U',
                style: TextStyle(color: Colors.blue[700]),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 输入框区域
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.3),
            blurRadius: 5,
            offset: Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 生成故事续写按钮
            Obx(() {
              // 只有在有对话内容时才显示按钮
              if (controller.displayMessages.length >= 2) {
                return Container(
                  margin: EdgeInsets.only(bottom: 8),
                  child: ElevatedButton.icon(
                    onPressed: () => controller.navigateToStoryGeneration(),
                    icon: Icon(Icons.auto_awesome, size: 20),
                    label: Text('生成故事续写'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.purple,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(24),
                      ),
                    ),
                  ),
                );
              }
              return SizedBox.shrink();
            }),
            
            // 输入框和发送按钮
            Row(
              children: [
                // 输入框
                Expanded(
                  child: TextField(
                    controller: textController,
                    decoration: InputDecoration(
                      hintText: '输入消息...',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(24),
                      ),
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 12,
                      ),
                    ),
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => _sendMessage(),
                  ),
                ),
                SizedBox(width: 8),

                // 发送按钮
                Obx(() {
                  if (controller.isSending.value) {
                    return Padding(
                      padding: EdgeInsets.all(12),
                      child: SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                    );
                  }

                  return IconButton(
                    icon: Icon(Icons.send),
                    color: Colors.blue,
                    onPressed: _sendMessage,
                  );
                }),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 发送消息
  void _sendMessage() {
    final text = textController.text.trim();
    if (text.isNotEmpty) {
      controller.sendMessage(text);
      textController.clear();
    }
  }

  /// 显示角色选择器
  void _showCharacterSelector() {
    // 创建一个局部的加载状态
    final isSelecting = false.obs;
    
    Get.bottomSheet(
      Builder(
        builder: (sheetContext) => Obx(() => WillPopScope(
          onWillPop: () async => !isSelecting.value,
          child: Stack(
            children: [
              // 主内容
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
                ),
                child: Column(
                  children: [
                    // 标题栏
                    Container(
                      padding: EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
                      ),
                      child: Row(
                        children: [
                          Text(
                            '选择角色',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Spacer(),
                          IconButton(
                            icon: Icon(Icons.refresh),
                            onPressed: isSelecting.value ? null : () => controller.loadCharacters(),
                          ),
                          IconButton(
                            icon: Icon(Icons.close),
                            onPressed: isSelecting.value ? null : () => Navigator.of(sheetContext).pop(),
                          ),
                        ],
                      ),
                    ),

                    // 角色列表
                    Expanded(
                      child: Obx(() {
                        if (controller.characters.isEmpty) {
                          return Center(
                            child: Text('暂无角色'),
                          );
                        }

                        return ListView.builder(
                          itemCount: controller.characters.length,
                          itemBuilder: (context, index) {
                            final character = controller.characters[index];
                            final isSelected =
                                controller.selectedCharacter.value == character;

                            return ListTile(
                              enabled: !isSelecting.value,
                              leading: CircleAvatar(
                                backgroundColor:
                                    isSelected ? Colors.blue : Colors.grey[300],
                                child: Text(
                                  character.name.isNotEmpty ? character.name[0] : '?',
                                  style: TextStyle(
                                    color: isSelected ? Colors.white : Colors.black,
                                  ),
                                ),
                              ),
                              title: Text(character.name),
                              subtitle: Text(
                                character.description ?? '无描述',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              selected: isSelected,
                              onTap: isSelecting.value ? null : () async {
                                print('🔘 点击角色: ${character.name}');
                                // 设置加载状态
                                isSelecting.value = true;
                                
                                try {
                                  print('⏳ 开始选择角色...');
                                  // 选择角色
                                  await controller.selectCharacter(character);
                                  print('✅ 选择角色完成');
                                  
                                } catch (e) {
                                  print('❌ 选择角色异常: $e');
                                } finally {
                                  print('🔄 开始关闭选择器...');
                                  // 先重置状态
                                  isSelecting.value = false;
                                  
                                  // 使用 SchedulerBinding 确保在下一帧关闭
                                  WidgetsBinding.instance.addPostFrameCallback((_) {
                                    try {
                                      print('   尝试使用 context.pop()');
                                      Navigator.of(sheetContext).pop();
                                      print('   ✅ 关闭成功');
                                    } catch (e) {
                                      print('   ❌ 关闭失败: $e');
                                    }
                                  });
                                }
                              },
                            );
                          },
                        );
                      }),
                    ),
                  ],
                ),
              ),
              
              // 加载遮罩
              if (isSelecting.value)
                Container(
                  color: Colors.black54,
                  child: Center(
                    child: Container(
                      padding: EdgeInsets.all(24),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          CircularProgressIndicator(),
                          SizedBox(height: 16),
                          Text(
                            '正在进入聊天...',
                            style: TextStyle(fontSize: 16),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
            ],
          ),
        )),
      ),
      isScrollControlled: true,
      isDismissible: true,
      enableDrag: true,
    );
  }

  /// 显示会话管理器（已废弃，现在自动管理会话）
  @Deprecated('会话现在自动管理，无需手动选择')
  void _showSessionManager() {
    if (controller.selectedCharacter.value == null) {
      Get.snackbar('提示', '请先选择角色');
      return;
    }

    Get.bottomSheet(
      Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          children: [
            // 标题栏
            Container(
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
              ),
              child: Row(
                children: [
                  Text(
                    '会话管理',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Spacer(),
                  IconButton(
                    icon: Icon(Icons.close),
                    onPressed: () => Get.back(),
                  ),
                ],
              ),
            ),

            // 新建会话按钮
            ListTile(
              leading: Icon(Icons.add_circle, color: Colors.blue),
              title: Text('新建会话'),
              onTap: () {
                Get.back();
                controller.createNewSession();
              },
            ),
            Divider(),

            // 会话列表
            Expanded(
              child: Obx(() {
                if (controller.chatSessions.isEmpty) {
                  return Center(
                    child: Text('暂无会话'),
                  );
                }

                return ListView.builder(
                  itemCount: controller.chatSessions.length,
                  itemBuilder: (context, index) {
                    final session = controller.chatSessions[index];
                    // ========== 修改：提取 file_name ==========
                    final sessionFileName = controller.extractFileName(session);
                    final isSelected =
                        controller.selectedSession.value == sessionFileName;
                    // =========================================

                    return ListTile(
                      leading: Icon(
                        Icons.chat_bubble,
                        color: isSelected ? Colors.blue : Colors.grey,
                      ),
                      title: Text(sessionFileName),
                      selected: isSelected,
                      onTap: () {
                        controller.selectSession(sessionFileName);
                        Get.back();
                      },
                    );
                  },
                );
              }),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
    );
  }

  /// 显示角色信息
  void _showCharacterInfo() {
    final character = controller.selectedCharacter.value;
    if (character == null) return;

    Get.dialog(
      AlertDialog(
        title: Text(character.name),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              if (character.description != null &&
                  character.description!.isNotEmpty) ...[
                Text(
                  '描述',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 4),
                Text(character.description!),
                SizedBox(height: 12),
              ],
              if (character.personality != null &&
                  character.personality!.isNotEmpty) ...[
                Text(
                  '性格',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 4),
                Text(character.personality!),
                SizedBox(height: 12),
              ],
              if (character.scenario != null &&
                  character.scenario!.isNotEmpty) ...[
                Text(
                  '场景',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 4),
                Text(character.scenario!),
                SizedBox(height: 12),
              ],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }
}

